import { PlusOutlined } from '@ant-design/icons-vue'
import {
  Button,
  Col,
  Form,
  FormItem,
  Image,
  Input,
  InputNumber,
  message,
  Radio,
  RadioGroup,
  RangePicker,
  Row,
  Spin
} from 'ant-design-vue'
import moment, { Moment } from 'moment'
import { defineComponent, ref } from 'vue'
import { useRoute } from 'vue-router'

import qzyApi from '@/apis/qzyApi'
import { PrizeItem, qzyLotteryItem } from '@/apis/qzyType'
import UploadFile from '@/components/UploadFile'
import { useBack } from '@/hooks'
import { isValueEmpty } from '@/utils'
import SelectYxGoods from '@/views/marketing/yxGoodsManage/hook/selectYxGoods'
export default defineComponent({
  name: 'QzyLotteryEdit',
  setup() {
    const route = useRoute()
    const loading = ref(false)
    const btnLoading = ref(false)
    const selectGoodsRef = ref({} as any)
    const modalTime = ref([] as any[])
    const activityName = ref('')
    const imgsrc = ref('')
    const disabledDate = (current: Moment) => {
      return current && current < moment().startOf('day')
    }
    const prizesList = ref([
      {},
      {},
      {},
      {},
      {},
      {},
      {},
      {},
      {}
    ] as qzyLotteryItem[])
    const { handleCancel } = useBack('refreshQzylotteryList')
    function cancel() {
      handleCancel()
    }
    //保存
    async function handleConfirm() {
      btnLoading.value = true
      if (!activityName.value) {
        message.error('请输入活动标题')
        btnLoading.value = false
        return
      }
      if (!modalTime.value) {
        message.error('请输入活动时间')
        btnLoading.value = false
        return
      }
      const prizes = prizesList.value
      let i = 0
      for (const Prizes of prizes) {
        i = i + 1
        if (i === 5) {
          continue
        }
        console.log(Prizes, i)
        if (Prizes.prizeType == null) {
          message.error('请输入完整奖项数据')
          btnLoading.value = false
          return
        }
        //类型为商品时提交校验
        if (
          Prizes.prizeType === 1 &&
          (isValueEmpty(Prizes.goodsName.trim()) ||
            isValueEmpty(Prizes.prizeName) ||
            isValueEmpty(Prizes.prizeUrl) ||
            isValueEmpty(Prizes.fragmentsFirst) ||
            isValueEmpty(Prizes.fragmentsSecond) ||
            isValueEmpty(Prizes.fragmentsThird) ||
            isValueEmpty(Prizes.winningProbability))
        ) {
          message.error('请输入完整奖项数据')
          btnLoading.value = false
          return
        }
        //类型为积分时提交校验
        if (
          Prizes.prizeType === 2 &&
          (isValueEmpty(Prizes.prizeName.trim()) ||
            isValueEmpty(Prizes.prizeUrl) ||
            isValueEmpty(Prizes.pointEnd) ||
            isValueEmpty(Prizes.pointStart))
        ) {
          message.error('请输入完整奖项数据')
          btnLoading.value = false
          return
        }
        //类型为谢谢参与时提交校验
        if (
          Prizes.prizeType === 0 &&
          (isValueEmpty(Prizes.prizeName.trim()) ||
            isValueEmpty(Prizes.prizeUrl))
        ) {
          message.error('请输入完整奖项数据')
          btnLoading.value = false
          return
        }
      }
      let sum = 0
      for (let i = 0; i < prizesList.value.length; i++) {
        if (i === 4) continue
        if (prizesList.value[i].prizeType != 0) {
          sum += prizesList.value[i].winningProbability
        }
      }
      if (sum != 100) {
        console.log(sum)
        message.error('中奖概率应为100%,请确认')
        btnLoading.value = false
        return
      }
      let newPrizesList: any = []
      newPrizesList = [...prizesList.value]
      ;[
        newPrizesList[5],
        newPrizesList[3],
        newPrizesList[7],
        newPrizesList[8],
        newPrizesList[6]
      ] = [
        newPrizesList[3],
        newPrizesList[8],
        newPrizesList[6],
        newPrizesList[5],
        newPrizesList[7]
      ]
      newPrizesList.splice(4, 1)
      if (route.query.id) {
        try {
          await qzyApi
            .editLotteryActivity({
              id: route.query.id,
              startTime:
                modalTime.value.length > 0
                  ? modalTime.value[0].format('x')
                  : '',
              endTime:
                modalTime.value.length > 1
                  ? modalTime.value[1].format('x')
                  : '',
              activityName: activityName.value,
              prizeList: newPrizesList
            })
            .then(() => {
              message.success('编辑成功')
              cancel()
            })
        } finally {
          btnLoading.value = false
        }
      } else {
        try {
          await qzyApi
            .createLotteryActivity({
              startTime:
                modalTime.value.length > 0
                  ? modalTime.value[0].format('x')
                  : '',
              endTime:
                modalTime.value.length > 1
                  ? modalTime.value[1].format('x')
                  : '',
              activityName: activityName.value,
              prizeList: newPrizesList
            })
            .then(() => {
              message.success('创建成功')
              cancel()
            })
        } finally {
          btnLoading.value = false
        }
      }
    }
    //图片索引
    const imgIndex = ref()
    //商品更改
    function onGoodsClick(index) {
      selectGoodsRef.value.show()
      imgIndex.value = index
    }
    //商品选中
    function onGoodsSelect(item) {
      if (item.stock < 0) {
        message.error('库存不足')
        return
      }
      Object.assign(prizesList.value[imgIndex.value], item)
      console.log(prizesList.value[imgIndex.value])
      console.log(item)
    }
    //编辑获取详情
    async function getEditData() {
      if (route.query.id) {
        loading.value = true
        try {
          const data = await qzyApi.qzyLotterylDetail({
            id: route.query.id
          })
          activityName.value = data.activityName
          modalTime.value = [moment(data.startTime), moment(data.endTime)]
          prizesList.value = [...data.prizeVos]
          // prizesList.value.prizeVos?.push({} as PrizeItem)
          // prizesList.value.
        } finally {
          let newPrizesList: any = []
          newPrizesList = prizesList.value
          loading.value = false
          ;[
            newPrizesList[5],
            newPrizesList[3],
            newPrizesList[4],
            newPrizesList[7],
            newPrizesList[8]
          ] = [
            newPrizesList[3],
            newPrizesList[7],
            newPrizesList[8],
            newPrizesList[5],
            newPrizesList[4]
          ]
        }
      }
    }
    getEditData()
    return {
      modalTime,
      loading,
      selectGoodsRef,
      activityName,
      imgsrc,
      prizesList,
      btnLoading,
      imgIndex,
      onGoodsSelect,
      onGoodsClick,
      disabledDate,
      handleConfirm,
      getEditData,
      cancel
    }
  },
  render() {
    return (
      <Spin spinning={this.loading}>
        <Form>
          <FormItem label="活动名称：">
            <Input
              style={{ width: '300px' }}
              maxlength={20}
              v-model:value={this.activityName}
            ></Input>
          </FormItem>
          <FormItem label="活动时间：">
            <RangePicker
              disabledDate={this.disabledDate}
              v-model:value={this.modalTime}
              showTime={{
                hideDisabledOptions: true,
                defaultValue: [
                  moment('00:00:00', 'HH:mm:ss'),
                  moment('23:59:59', 'HH:mm:ss')
                ]
              }}
              format={'YYYY-MM-DD HH:mm:ss'}
              separator={'至'}
              style={{ width: '400px' }}
            />
          </FormItem>
          <span>奖项：</span>
          <Row type="flex" gutter={[8, 8]}>
            {this.prizesList.map((item, index) => {
              const viewPrize = (
                <Col span={7}>
                  <div
                    style={{
                      width: '300px',
                      height: '500px',
                      border: ' 1px solid black',
                      display: 'flex',
                      justifyContent: 'center',
                      flexDirection: 'column'
                    }}
                  >
                    <FormItem
                      label="奖项名称"
                      style={{
                        width: '250px',
                        marginBottom: '20px',
                        marginLeft: '15px'
                      }}
                    >
                      <Input
                        maxlength={6}
                        v-model:value={item.prizeName}
                      ></Input>
                    </FormItem>
                    <FormItem
                      label="类型"
                      style={{ marginBottom: '15px', marginLeft: '15px' }}
                    >
                      <RadioGroup
                        v-model:value={item.prizeType}
                        style={{ marginLeft: '25px' }}
                      >
                        <Radio value={1} style={{ display: 'block' }}>
                          商品
                        </Radio>
                        <Radio value={2} style={{ display: 'block' }}>
                          积分
                        </Radio>
                        {/* <Radio value={3} style={{ display: 'block' }}>
                        金豆
                      </Radio> */}
                        <Radio value={0} style={{ display: 'block' }}>
                          谢谢参与
                        </Radio>
                      </RadioGroup>
                    </FormItem>
                    <div v-show={item.prizeType === 1}>
                      <FormItem
                        style={{ marginBottom: '22px', marginLeft: '15px' }}
                      >
                        <div style={{ display: 'flex' }}>
                          <Button
                            style={{ width: '75px', height: '70px' }}
                            onClick={() => this.onGoodsClick(index)}
                            v-show={!item.stock}
                          >
                            <PlusOutlined />
                          </Button>
                          <div v-show={item.stock}>
                            <Image
                              style={{ width: '75px', height: '70px' }}
                              src={item.prizeUrl}
                            ></Image>
                          </div>
                          <span
                            style={{
                              marginRight: '15px',
                              marginTop: '7px',
                              marginLeft: '10px'
                            }}
                            v-show={item.goodsName}
                          >
                            {item.goodsName}
                          </span>
                        </div>
                        <span
                          style={{
                            position: 'absolute',
                            bottom: '0px',
                            left: '30%'
                          }}
                          v-show={item.goodsName}
                        >
                          库存：{item.stock}
                        </span>
                      </FormItem>
                      <FormItem
                        label="碎片1"
                        style={{ marginBottom: '0px', marginLeft: '15px' }}
                      >
                        <InputNumber
                          precision={0}
                          v-model:value={item.fragmentsFirst}
                        ></InputNumber>
                      </FormItem>
                      <FormItem
                        label="碎片2"
                        style={{ marginBottom: '0px', marginLeft: '15px' }}
                      >
                        <InputNumber
                          precision={0}
                          v-model:value={item.fragmentsSecond}
                        ></InputNumber>
                      </FormItem>
                      <FormItem label="碎片3" style={{ marginLeft: '15px' }}>
                        <InputNumber
                          precision={0}
                          v-model:value={item.fragmentsThird}
                        ></InputNumber>
                      </FormItem>
                      <FormItem
                        v-show={item.stock}
                        style={{
                          marginLeft: '15px'
                        }}
                      >
                        <Button
                          type="primary"
                          style={{ width: '100px', height: '38px' }}
                          onClick={() => this.onGoodsClick(index)}
                        >
                          替换商品
                        </Button>
                      </FormItem>
                      <FormItem
                        style={{ marginLeft: '15px', marginTop: '5px' }}
                      >
                        中奖概率：
                        <InputNumber
                          max={100}
                          min={0}
                          precision={0}
                          style={{ width: '70px', marginRight: '5px' }}
                          v-model:value={item.winningProbability}
                        ></InputNumber>
                        %（0~100）
                      </FormItem>
                    </div>
                    <div v-show={item.prizeType === 2 || item.prizeType === 3}>
                      <FormItem
                        label={
                          item.prizeType === 2
                            ? '积分'
                            : item.prizeType === 3
                            ? '金豆'
                            : ''
                        }
                        style={{ marginLeft: '15px' }}
                      >
                        <InputNumber
                          precision={0}
                          style={{
                            width: '70px',
                            marginRight: '5px',
                            marginLeft: '15px'
                          }}
                          v-model:value={item.pointStart}
                        ></InputNumber>
                        ~
                        <InputNumber
                          precision={0}
                          style={{ width: '70px', marginLeft: '5px' }}
                          v-model:value={item.pointEnd}
                        ></InputNumber>
                        <div
                          style={{ marginLeft: '15px', marginBottom: '10px' }}
                        >
                          (随机发放范围内的积分)
                        </div>
                      </FormItem>
                      <FormItem label="奖项图片" style={{ marginLeft: '15px' }}>
                        <UploadFile v-model={[item.prizeUrl, 'urls']}>
                          上传图片
                        </UploadFile>
                      </FormItem>
                      <FormItem style={{ marginLeft: '15px' }}>
                        中奖概率：
                        <InputNumber
                          max={100}
                          min={0}
                          precision={0}
                          style={{ width: '70px', marginRight: '5px' }}
                          v-model:value={item.winningProbability}
                        ></InputNumber>
                        %（0~100）
                      </FormItem>
                    </div>
                    <div v-show={item.prizeType === 0}>
                      <FormItem label="奖项图片" style={{ marginLeft: '15px' }}>
                        <UploadFile v-model={[item.prizeUrl, 'urls']}>
                          上传图片
                        </UploadFile>
                      </FormItem>
                    </div>
                  </div>
                </Col>
              )
              const viewEmpty = (
                <Col span={7}>
                  <div
                    style={{
                      width: '300px',
                      height: '500px'
                    }}
                  ></div>
                </Col>
              )
              return index == 4 ? viewEmpty : viewPrize
            })}

            <FormItem style={{ marginLeft: '430px', marginTop: '20px' }}>
              <Button
                style={{ width: '200px', height: '45px' }}
                onClick={this.cancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                style={{ width: '200px', height: '45px', marginLeft: '70px' }}
                onClick={this.handleConfirm}
                loading={this.btnLoading}
              >
                确认
              </Button>
            </FormItem>
          </Row>
        </Form>
        <SelectYxGoods
          ref="selectGoodsRef"
          goodsPlatform={1}
          status={2}
          onSelect={this.onGoodsSelect}
        />
      </Spin>
    )
  }
})
